package com.xiaoaoc.SmartToilet.service;

import com.xiaoaoc.SmartToilet.model.User;
import com.xiaoaoc.SmartToilet.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Optional<User> findByUserName(String username) {
        return userRepository.findByUserName(username);
    }

    //Register
    public User register(User user) {
        user.setCreatedAt(new Date());
        return userRepository.save(user);
    }

    //Login
    public User login(String userName,String userPassword) {
        Optional<User> user = userRepository.findByUserName(userName);
        if (user.isPresent()) {
            if (user.get().getUserPassword().equals(userPassword)) {
                return user.get();
            }
            else
                return null;
        }
        return null;
    }

    public User changeAvatarUrl(String userName,String avatarUrl) {
        Optional<User> user = userRepository.findByUserName(userName);
        if (user.isPresent()) {
            user.get().setAvatarUrl(avatarUrl);
            user.get().setUpdatedAt(new Date());
            userRepository.save(user.get());
            return user.get();
        }
            else{
                return null;
        }
    }
}
